import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag, Switch, DatePicker } from 'tdesign-react';
import { SearchIcon, AddIcon, EditIcon, DeleteIcon, RefreshIcon, ArrowUpIcon } from 'tdesign-icons-react';
import { JupiterArticle, JupiterArticleQuery, JupiterArticleForm } from '../../types/articleTypes';
import { formatTime } from '../../utils/timeutil';
import {
    fetchArticleList,
    createArticle,
    updateArticle,
    deleteArticle,
    publishArticle,
    archiveArticle,
    topArticle
} from '../../services/articleService';
import ArticleForm from './components/ArticleForm';

export default function ArticlePage() {
    const [articleList, setArticleList] = useState<JupiterArticle[]>([]);
    const [loading, setLoading] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [editingArticle, setEditingArticle] = useState<Partial<JupiterArticle>>();
    const [title, setTitle] = useState('新增文章');

    // 搜索条件
    const [searchTitle, setSearchTitle] = useState('');
    const [searchAuthor, setSearchAuthor] = useState('');
    const [searchCategory, setSearchCategory] = useState('');
    const [searchStatus, setSearchStatus] = useState('');
    const [searchTag, setSearchTag] = useState('');
    const [searchReadType, setSearchReadType] = useState('');
    const [searchIsOriginal, setSearchIsOriginal] = useState('');
    const [searchIsCarousel, setSearchIsCarousel] = useState('');
    const [searchIsRecommend, setSearchIsRecommend] = useState('');

    // 分页
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    // 状态选项
    const statusOptions = [
        { label: '草稿', value: 'DRAFT' },
        { label: '已发布', value: 'PUBLISHED' },
        { label: '已归档', value: 'ARCHIVED' },
    ];

    const getList = async () => {
        setLoading(true);
        try {
            const params: JupiterArticleQuery = {
                title: searchTitle || undefined,
                author: searchAuthor || undefined,
                categoryUuid: searchCategory || undefined,
                status: searchStatus || undefined,
                tagUuid: searchTag || undefined,
                page: pagination.current,
                size: pagination.pageSize,
            };
            const response = await fetchArticleList(params);
            if (response.code === 200) {
                setArticleList(response.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    total: response.data.total || 0,
                }));
            }
        } catch (error) {
            MessagePlugin.error('获取文章列表失败');
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleReset = () => {
        setSearchTitle('');
        setSearchAuthor('');
        setSearchCategory('');
        setSearchStatus('');
        setSearchTag('');
        setSearchReadType('');
        setSearchIsOriginal('');
        setSearchIsCarousel('');
        setSearchIsRecommend('');
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleCreate = () => {
        setEditingArticle({});
        setTitle('新增文章');
        setFormVisible(true);
    };

    const handleEdit = (record: JupiterArticle) => {
        setEditingArticle(record);
        setTitle('编辑文章');
        setFormVisible(true);
    };

    const handleDelete = (record: JupiterArticle) => {
        DialogPlugin.confirm({
            header: '确认删除',
            body: `确定要删除文章"${record.title}"吗？`,
            onConfirm: async () => {
                try {
                    const response = await deleteArticle(record.uuid);
                    if (response.code === 200) {
                        MessagePlugin.success('删除成功');
                        getList();
                    } else {
                        MessagePlugin.error(response.message || '删除失败');
                    }
                } catch (error) {
                    MessagePlugin.error('删除失败');
                }
            },
        });
    };

    const handlePublish = (record: JupiterArticle) => {
        DialogPlugin.confirm({
            header: '确认发布',
            body: `确定要发布文章"${record.title}"吗？`,
            onConfirm: async () => {
                try {
                    const response = await publishArticle(record.uuid);
                    if (response.code === 200) {
                        MessagePlugin.success('发布成功');
                        getList();
                    } else {
                        MessagePlugin.error(response.message || '发布失败');
                    }
                } catch (error) {
                    MessagePlugin.error('发布失败');
                }
            },
        });
    };

    const handleArchive = (record: JupiterArticle) => {
        DialogPlugin.confirm({
            header: '确认归档',
            body: `确定要归档文章"${record.title}"吗？`,
            onConfirm: async () => {
                try {
                    const response = await archiveArticle(record.uuid);
                    if (response.code === 200) {
                        MessagePlugin.success('归档成功');
                        getList();
                    } else {
                        MessagePlugin.error(response.message || '归档失败');
                    }
                } catch (error) {
                    MessagePlugin.error('归档失败');
                }
            },
        });
    };

    const handleTop = async (record: JupiterArticle) => {
        try {
            const response = await topArticle(record.uuid, !record.isTop);
            if (response.code === 200) {
                MessagePlugin.success(record.isTop ? '取消置顶成功' : '置顶成功');
                getList();
            } else {
                MessagePlugin.error(response.message || '操作失败');
            }
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handleFormSubmit = async (formData: JupiterArticleForm) => {
        try {
            let response;
            if (editingArticle?.uuid) {
                response = await updateArticle(editingArticle.uuid, formData);
            } else {
                response = await createArticle(formData);
            }

            if (response.code === 200) {
                MessagePlugin.success(editingArticle?.uuid ? '更新成功' : '创建成功');
                setFormVisible(false);
                getList();
            } else {
                MessagePlugin.error(response.message || '操作失败');
            }
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handlePageChange = (pageInfo: any) => {
        setPagination(prev => ({
            ...prev,
            current: pageInfo.current,
            pageSize: pageInfo.pageSize,
        }));
    };

    const getStatusTag = (status: string) => {
        const statusMap = {
            DRAFT: { theme: 'default', text: '草稿' },
            PUBLISHED: { theme: 'success', text: '已发布' },
            ARCHIVED: { theme: 'warning', text: '已归档' },
        };
        const config = statusMap[status as keyof typeof statusMap] || { theme: 'default', text: status };
        return <Tag theme={config.theme as any}>{config.text}</Tag>;
    };

    const columns = [
        {
            colKey: 'title',
            title: '标题',
            width: 200,
            cell: ({ row }: any) => (
                <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {row.title}
                </div>
            ),
        },
        {
            colKey: 'author',
            title: '作者',
            width: 100,
        },
        {
            colKey: 'categoryName',
            title: '分类',
            width: 120,
        },
        {
            colKey: 'tagNames',
            title: '标签',
            width: 150,
            cell: ({ row }: any) => (
                <div>
                    {row.tagNames?.map((tag: string, index: number) => (
                        <Tag key={index} size="small" style={{ marginRight: 4, marginBottom: 4 }}>
                            {tag}
                        </Tag>
                    ))}
                </div>
            ),
        },
        {
            colKey: 'status',
            title: '状态',
            width: 100,
            cell: ({ row }: any) => getStatusTag(row.status),
        },
        {
            colKey: 'isTop',
            title: '置顶',
            width: 80,
            cell: ({ row }: any) => (row.isTop ? <Tag theme="danger">置顶</Tag> : ''),
        },
        {
            colKey: 'readType',
            title: '权限',
            width: 80,
            cell: ({ row }: any) => (
                <Tag theme={row.readType === 0 ? 'success' : 'warning'}>
                    {row.readType === 0 ? '公开' : '私密'}
                </Tag>
            ),
        },
        {
            colKey: 'isOriginal',
            title: '原创',
            width: 80,
            cell: ({ row }: any) => (row.isOriginal ? <Tag theme="primary">原创</Tag> : <Tag theme="default">转载</Tag>),
        },
        {
            colKey: 'isCarousel',
            title: '轮播',
            width: 80,
            cell: ({ row }: any) => (row.isCarousel ? <Tag theme="success">轮播</Tag> : ''),
        },
        {
            colKey: 'isRecommend',
            title: '推荐',
            width: 80,
            cell: ({ row }: any) => (row.isRecommend ? <Tag theme="warning">推荐</Tag> : ''),
        },
        {
            colKey: 'viewCount',
            title: '浏览量',
            width: 80,
        },
        {
            colKey: 'likeCount',
            title: '点赞数',
            width: 80,
        },
        {
            colKey: 'commentCount',
            title: '评论数',
            width: 80,
        },
        {
            colKey: 'publishTime',
            title: '发布时间',
            width: 180,
            cell: ({ row }: any) => row.publishTime ? formatTime(row.publishTime) : '-',
        },
        {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }: any) => formatTime(row.createTime),
        },
        {
            colKey: 'operation',
            title: '操作',
            width: 200,
            cell: ({ row }: any) => (
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    <Button
                        theme="primary"
                        variant="text"
                        size="small"
                        icon={<EditIcon />}
                        onClick={() => handleEdit(row)}
                    >
                        编辑
                    </Button>
                    {row.status === 'DRAFT' && (
                        <Button
                            theme="success"
                            variant="text"
                            size="small"
                            onClick={() => handlePublish(row)}
                        >
                            发布
                        </Button>
                    )}
                    {row.status === 'PUBLISHED' && (
                        <Button
                            theme="warning"
                            variant="text"
                            size="small"
                            onClick={() => handleArchive(row)}
                        >
                            归档
                        </Button>
                    )}
                    <Button
                        theme={row.isTop ? "warning" : "default"}
                        variant="text"
                        size="small"
                        icon={<ArrowUpIcon />}
                        onClick={() => handleTop(row)}
                    >
                        {row.isTop ? '取消置顶' : '置顶'}
                    </Button>
                    <Button
                        theme="danger"
                        variant="text"
                        size="small"
                        icon={<DeleteIcon />}
                        onClick={() => handleDelete(row)}
                    >
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    useEffect(() => {
        getList();
    }, [pagination.current, pagination.pageSize]);

    return (
        <Card title="文章管理">
            {/* 搜索区域 */}
            <div style={{ marginBottom: 16, padding: '16px 0', borderBottom: '1px solid #e7e7e7' }}>
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    <Input
                        placeholder="文章标题"
                        value={searchTitle}
                        onChange={(value) => setSearchTitle(value as string)}
                        style={{ width: 200 }}
                    />
                    <Input
                        placeholder="作者"
                        value={searchAuthor}
                        onChange={(value) => setSearchAuthor(value as string)}
                        style={{ width: 150 }}
                    />
                    <Input
                        placeholder="分类"
                        value={searchCategory}
                        onChange={(value) => setSearchCategory(value as string)}
                        style={{ width: 150 }}
                    />
                    <Select
                        placeholder="状态"
                        value={searchStatus}
                        onChange={(value) => setSearchStatus(value as string)}
                        style={{ width: 120 }}
                        options={statusOptions}
                        clearable
                    />
                    <Input
                        placeholder="标签"
                        value={searchTag}
                        onChange={(value) => setSearchTag(value as string)}
                        style={{ width: 150 }}
                    />
                    <Select
                        placeholder="权限"
                        value={searchReadType}
                        onChange={(value) => setSearchReadType(value as string)}
                        style={{ width: 100 }}
                        options={[
                            { label: '公开', value: '0' },
                            { label: '私密', value: '1' },
                        ]}
                        clearable
                    />
                    <Select
                        placeholder="原创"
                        value={searchIsOriginal}
                        onChange={(value) => setSearchIsOriginal(value as string)}
                        style={{ width: 100 }}
                        options={[
                            { label: '原创', value: 'true' },
                            { label: '转载', value: 'false' },
                        ]}
                        clearable
                    />
                    <Select
                        placeholder="轮播"
                        value={searchIsCarousel}
                        onChange={(value) => setSearchIsCarousel(value as string)}
                        style={{ width: 100 }}
                        options={[
                            { label: '是', value: 'true' },
                            { label: '否', value: 'false' },
                        ]}
                        clearable
                    />
                    <Select
                        placeholder="推荐"
                        value={searchIsRecommend}
                        onChange={(value) => setSearchIsRecommend(value as string)}
                        style={{ width: 100 }}
                        options={[
                            { label: '是', value: 'true' },
                            { label: '否', value: 'false' },
                        ]}
                        clearable
                    />
                    <Button theme="primary" icon={<SearchIcon />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button theme="default" onClick={handleReset}>
                        重置
                    </Button>
                </div>
            </div>

            {/* 操作按钮 */}
            <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
                    新增文章
                </Button>
            </div>

            {/* 表格 */}
            <Table
                data={articleList}
                rowKey="uuid"
                columns={columns}
                loading={loading}
                pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    onChange: handlePageChange,
                }}
            />

            {/* 表单弹窗 */}
            <ArticleForm
                visible={formVisible}
                title={title}
                editingData={editingArticle}
                onClose={() => setFormVisible(false)}
                onSubmit={handleFormSubmit}
            />
        </Card>
    );
}